﻿using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlanDetail;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class ProductPlanMain : Form
    {

       
        [DllImport("gdi32.dll")]
        private static extern IntPtr CreateRoundRectRgn(int nLeftRect, int nTopRect, int nRightRect, int nBottomRect, int nWidthEllipse, int nHeightEllipse);

        public ProductPlanMain()
        {
            InitializeComponent();
            SetFormIcon();
            InitializeForm();
        }
        

        
        private void InitializeForm()
        {
            this.Text = "生产计划";
            this.Size = new Size(1400, 650); // 增加窗体宽度以显示所有列
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.Sizable; // 改为可调整大小
            this.MaximizeBox = true; // 允许最大化
            this.MinimizeBox = true; // 允许最小化
            
            // 禁用DataGridView的列重新排序功能
            dgvPlanList.AllowUserToOrderColumns = false;
            
            // 设置DataGridView的Dock属性，使其能够适应窗体大小
            dgvPlanList.Dock = DockStyle.Fill;
            
            // 设置其他控件的Anchor属性，使其能够随窗体大小调整
            SetupControlAnchors();
            
            // 添加窗体大小改变事件
            this.SizeChanged += ProductPlanMain_SizeChanged;
        }
        
        /// <summary>
        /// 设置控件的Anchor属性，使其能够随窗体大小调整
        /// </summary>
        private void SetupControlAnchors()
        {
            // 设置TabControl的Dock属性
            skinTabControl1.Dock = DockStyle.Fill;
            
            // 设置TabPage的Dock属性
            skinTabPage1.Dock = DockStyle.Fill;
            
            // 设置搜索区域控件的Anchor属性
            if (lblProductCode != null) lblProductCode.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (txtProductCode != null) txtProductCode.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductName != null) lblProductName.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (txtProductName != null) txtProductName.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductResource != null) lblProductResource.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (cboProductResource != null) cboProductResource.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (lblProductState != null) lblProductState.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (cboProductState != null) cboProductState.Anchor = AnchorStyles.Top | AnchorStyles.Left;
            if (btnReset != null) btnReset.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            if (btnSearch != null) btnSearch.Anchor = AnchorStyles.Top | AnchorStyles.Right;
            
            // 设置分页控件的Anchor属性
            if (lblTotalCount != null) lblTotalCount.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (lblTotalPage != null) lblTotalPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnFirstPage != null) btnFirstPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnPreviousPage != null) btnPreviousPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnNextPage != null) btnNextPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnLastPage != null) btnLastPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (txtPageNumber != null) txtPageNumber.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
            if (btnGoPage != null) btnGoPage.Anchor = AnchorStyles.Bottom | AnchorStyles.Left;
        }
        
        /// <summary>
        /// 窗体大小改变事件处理
        /// </summary>
        private void ProductPlanMain_SizeChanged(object sender, EventArgs e)
        {
            // 调整DataGridView的列宽以适应新的窗体宽度
            AdjustDataGridViewColumns();
            
            // 如果窗体最大化，进行特殊处理
            if (this.WindowState == FormWindowState.Maximized)
            {
                HandleMaximizedState();
            }
        }
        
        /// <summary>
        /// 处理窗体最大化状态
        /// </summary>
        private void HandleMaximizedState()
        {
            // 确保DataGridView充分利用可用空间
            if (dgvPlanList != null)
            {
                // 设置DataGridView的Dock属性为Fill，确保它填充整个可用空间
                dgvPlanList.Dock = DockStyle.Fill;
                
                // 调整列宽以充分利用最大化后的空间
                AdjustDataGridViewColumns();
                
                // 刷新DataGridView以确保正确显示
                dgvPlanList.Refresh();
            }
        }
        
        /// <summary>
        /// 调整DataGridView列宽以适应窗体大小
        /// </summary>
        private void AdjustDataGridViewColumns()
        {
            if (dgvPlanList != null && dgvPlanList.Columns.Count > 0)
            {
                // 设置DataGridView的AutoSizeColumnsMode为Fill，让列自动填充可用空间
                dgvPlanList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                
                // 为特定列设置最小宽度和最大宽度
                foreach (DataGridViewColumn column in dgvPlanList.Columns)
                {
                    // 根据列的内容类型设置不同的宽度限制
                    switch (column.HeaderText)
                    {
                        case "修改":
                        case "删除":
                        case "详情":
                            column.MinimumWidth = 60;
                            column.Width = 80;
                            break;
                        case "计划编号":
                        case "产品编号":
                            column.MinimumWidth = 100;
                            break;
                        case "计划名称":
                        case "产品名称":
                            column.MinimumWidth = 120;
                            break;
                        case "规格型号":
                            column.MinimumWidth = 100;
                            break;
                        case "计划开工时间":
                        case "计划完工时间":
                        case "需求日期":
                            column.MinimumWidth = 120;
                            break;
                        case "计划数量":
                            column.MinimumWidth = 80;
                            break;
                        case "单位":
                            column.MinimumWidth = 60;
                            break;
                        default:
                            column.MinimumWidth = 80;
                            break;
                    }
                }
                
                // 强制重新计算列宽
                dgvPlanList.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            }
        }
       
      

        /// <summary>
        /// 设置窗体图标
        /// </summary>
        private void SetFormIcon()
        {
            
                string[] possiblePaths = {
                    System.IO.Path.Combine(Application.StartupPath, "..", "..", "Images", "ww.ico")
                };

                string iconPath = possiblePaths.FirstOrDefault(System.IO.File.Exists);
                if (!string.IsNullOrEmpty(iconPath))
                {
                    this.Icon = new System.Drawing.Icon(iconPath);
                }
           
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReset_Click(object sender, EventArgs e)
        {
            txtProductCode.Text= string.Empty;
            txtProductName.Text= string.Empty;
            if(cboProductResource.Items.Count>0)
            {
                cboProductResource.SelectedIndex = 0;
            }
            if(cboProductState.Items.Count>0)
            {
                cboProductState.SelectedIndex = 0;
            }
        }
        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                string baseUrl = "http://localhost:5281/api/Plan/GetPlan";

                string planCode=txtProductCode.Text.Trim();
                string planName=txtProductName.Text.Trim();
                string resource = cboProductResource.SelectedValue?.ToString();
                string planState = cboProductState.SelectedValue?.ToString();

                var queryParams = new List<string>();
                if (!string.IsNullOrEmpty(planCode)) queryParams.Add(string.Format("planCode={0}", planCode));
                if (!string.IsNullOrEmpty(planName)) queryParams.Add(string.Format("planName={0}", planName));
                if (!string.IsNullOrEmpty(resource)) queryParams.Add(string.Format("resource={0}", resource));
                if (!string.IsNullOrEmpty(planState)) queryParams.Add(string.Format("planState={0}", planState));

                queryParams.Add(string.Format("pageIndex={0}", pageIndex));
                queryParams.Add(string.Format("pageSize={0}", pageSize));

                string fullUrl = string.Format("{0}?{1}", baseUrl, string.Join("&", queryParams));

                using (HttpClient client=new HttpClient())
                {
                    HttpResponseMessage response=await client.GetAsync(fullUrl);
                    response.EnsureSuccessStatusCode();
                    string jsonResponse=await response.Content.ReadAsStringAsync();
                    ApiResponse apiResponse = JsonConvert.DeserializeObject<ApiResponse>(jsonResponse);
                    if (apiResponse.code==200)
                    {
                        // 确保数据是List<PlanData>类型
                        if (apiResponse.data is List<PlanData> planList)
                        {
                            dgvPlanList.DataSource = planList;
                        }
                        else
                        {
                            // 如果不是正确的类型，尝试转换
                            var planDataList = JsonConvert.DeserializeObject<List<PlanData>>(JsonConvert.SerializeObject(apiResponse.data));
                            dgvPlanList.DataSource = planDataList;
                        }
                        
                        // 隐藏不需要显示的列
                        if (dgvPlanList.Columns.Contains("createName"))
                        {
                            dgvPlanList.Columns["createName"].Visible = false;
                        }
                        if (dgvPlanList.Columns.Contains("createDate"))
                        {
                            dgvPlanList.Columns["createDate"].Visible = false;
                        }
                        if (dgvPlanList.Columns.Contains("productId"))
                        {
                            dgvPlanList.Columns["productId"].Visible = false;
                        }
                        if (dgvPlanList.Columns.Contains("state"))
                        {
                            dgvPlanList.Columns["state"].Visible = false;
                        }
                        if (dgvPlanList.Columns.Contains("isDel"))
                        {
                            dgvPlanList.Columns["isDel"].Visible = false;
                        }
                       
                      
                        totalCount =apiResponse.totalCount;
                        totalPage=apiResponse.totalPage;

                        lblTotalCount.Text = string.Format("共{0}条", totalCount);
                        lblTotalPage.Text = string.Format("第{0}页/共{1}页", pageIndex, totalPage);

                        UpdatePagingButtons();
                      
                        // 在数据加载完成后调整列宽
                        this.BeginInvoke(new Action(() => {
                            AdjustDataGridViewColumns();
                        }));
                       
                    }
                    else
                    {
                        MessageBox.Show(string.Format("查询失败{0}", apiResponse.msg));
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"查询异常: {ex.Message}");
                MessageBox.Show(string.Format("查询失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
           
            // 获取订单来源的值
            string productSource = null; // 默认设置为 null
            if (cboProductResource.SelectedValue != null)
            {
                // 只有当选中项的Value不为0（非"请选择"）时，才获取它的值
                if ((int)cboProductResource.SelectedValue != 0)
                {
                    productSource = cboProductResource.SelectedValue.ToString();
                }
            }

            // 获取状态的值
            string planstate = null; // 默认设置为 null
            if (cboProductState.SelectedValue != null)
            {
                // 只有当选中项的Value不为0（非"请选择"）时，才获取它的值
                if ((int)cboProductState.SelectedValue != 0)
                {
                    planstate = cboProductState.SelectedValue.ToString();
                }
            }

        }
        /// <summary>
        /// 分页默认值
        /// </summary>
        private int pageIndex = 1;
        private int pageSize = 15;
        private int totalCount = 0;
        private int totalPage = 0;
        private void UpdatePagingButtons()
        {
            btnFirstPage.Enabled = pageIndex > 1;
            btnPreviousPage.Enabled = pageIndex > 1;
            btnNextPage.Enabled = pageIndex < totalPage;
            btnLastPage.Enabled = pageIndex < totalPage;
        }
        /// <summary>
        /// 首页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFirstPage_Click(object sender, EventArgs e)
        {
            if(pageIndex!=1)
            {
                pageIndex = 1;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreviousPage_Click(object sender, EventArgs e)
        {
            if (pageIndex>1)
            {
                pageIndex--;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if(pageIndex<totalPage)
            {
                pageIndex++;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 尾页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnLastPage_Click(object sender, EventArgs e)
        {
            if(pageIndex!=totalPage)
            {
                pageIndex=totalPage;
                btnSearch_Click(sender, e);
            }
        }
        /// <summary>
        /// 跳转页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGoPage_Click(object sender, EventArgs e)
        {
            if (int.TryParse(txtPageNumber.Text, out int pageNum) && pageNum >= 1 && pageNum <= totalPage)
            {
                pageIndex = pageNum;
                btnSearch_Click(sender, e);
            }
            else
            {
                MessageBox.Show("请输入有效的页码。");
            }
        }
        /// <summary>
        /// 查询的下拉框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void ProductPlanMain_Load(object sender, EventArgs e)
        {
           
            btnSearch_Click(sender, e);
            
            // 注意：SetColumnOrder已经在btnSearch_Click中调用了，这里不需要重复调用
         
            var sourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboProductResource.DataSource = sourceList;
            cboProductResource.DisplayMember = "Name";
            cboProductResource.ValueMember = "Value";
            cboProductResource.SelectedIndex = 0;
            int selectedValue=(int)cboProductResource.SelectedValue;

            // 为新增表单的来源类型下拉框设置选项
            var resourceList = new List<OrderSource>
            {
                new OrderSource { Value = 0, Name = "请选择来源类型" },
                new OrderSource { Value = 1, Name = "销售订单" },
                new OrderSource { Value = 2, Name = "库存备货" },
                new OrderSource { Value = 3, Name = "其他" }
            };
            cboResource.DataSource = resourceList;
            cboResource.DisplayMember = "Name";
            cboResource.ValueMember = "Value";
            cboResource.SelectedIndex = 0;

            var state = new List<PlanState>
            {
                new PlanState { Value = 0, PlanName = "请选择" },
                new PlanState { Value = 1, PlanName = "未分解" },
                new PlanState { Value = 2, PlanName = "已完成" },
                new PlanState { Value = 3, PlanName = "已撤回" }
            };
            cboProductState.DataSource = state;
            cboProductState.DisplayMember = "PlanName";
            cboProductState.ValueMember = "Value";
            cboProductState.SelectedIndex = 0;
            int selectedValues = (int)cboProductState.SelectedValue;
            
            // 在数据加载完成后调整列宽
            this.BeginInvoke(new Action(() => {
                AdjustDataGridViewColumns();
            }));
            
        }
        /// <summary>
        /// 显示的来源类型列和状态列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvPlanList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            // 检查是否是来源类型列或状态列
            if (e.ColumnIndex >= 0 && e.ColumnIndex < dgvPlanList.Columns.Count)
            {
                var column = dgvPlanList.Columns[e.ColumnIndex];
                
                // 处理来源类型列
                if (column.DataPropertyName == "resource" && e.Value != null)
                {
                    // 尝试将单元格的值转换为 int
                    if (int.TryParse(e.Value.ToString(), out int resourceValue))
                    {
                        // 根据 int 值返回对应的中文文本
                        switch (resourceValue)
                        {
                            case 1:
                                e.Value = "销售订单";
                                break;
                            case 2:
                                e.Value = "库存备货";
                                break;
                            case 3:
                                e.Value = "其他";
                                break;
                            default:
                                e.Value = "未知";
                                break;
                        }

                        // 告诉事件处理程序，我们已经处理了格式化，不需要进行默认的格式化操作
                        e.FormattingApplied = true;
                    }
                }
                
                // 处理状态列
                if (column.DataPropertyName == "planState" && e.Value != null)
                {
                    // 尝试将单元格的值转换为 int
                    if (int.TryParse(e.Value.ToString(), out int stateValue))
                    {
                        // 根据 int 值返回对应的中文文本
                        switch (stateValue)
                        {
                            case 1:
                                e.Value = "未分解";
                                break;
                            case 2:
                                e.Value = "已完成";
                                break;
                            case 3:
                                e.Value = "已撤回";
                                break;
                            default:
                                e.Value = "未知";
                                break;
                        }

                        // 告诉事件处理程序，我们已经处理了格式化，不需要进行默认的格式化操作
                        e.FormattingApplied = true;
                    }
                }
            }
        }
        /// <summary>
        /// 新增产品名称后的按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnProductName_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建产品选择窗体
                var selectProductForm = new SelectProduct();
                if (selectProductForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了产品，将产品信息填充到对应的输入框
                    if (selectProductForm.SelectedProduct != null)
                    {
                        var product = selectProductForm.SelectedProduct;
                        txtproname.Text = product.ProductName; // 成品名称
                        txtspecifi.Text = product.Specification; // 规格型号
                        txtunit.Text = product.UnitName; // 单位
                        txtProcode.Text = product.ProductCode; // 成品编号
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开产品选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增订单编号后的按钮
        /// </summary>
        private void btnOrderNumber_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建销售订单选择窗体
                var selectSaleForm = new SelectSale();
                if (selectSaleForm.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户选择了销售订单，将订单信息填充到对应的输入框
                    if (selectSaleForm.SelectedSale != null)
                    {
                        var sale = selectSaleForm.SelectedSale;
                        txtOrderCode.Text = sale.SalesOrderId.ToString(); // 订单编号显示销售单Id
                      
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("打开销售订单选择窗口失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 新增计划
        /// </summary>
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                // 验证必填字段
                if (string.IsNullOrWhiteSpace(txtPlanCode.Text))
                {
                    MessageBox.Show("请输入计划编号", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPlanCode.Focus();
                    return;
                }

                if (string.IsNullOrWhiteSpace(txtPlanName.Text))
                {
                    MessageBox.Show("请输入计划名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtPlanName.Focus();
                    return;
                }

                // 创建PlanData对象
                var planData = new PlanData
                {
                    planCode = txtPlanCode.Text.Trim(),
                    planName = txtPlanName.Text.Trim(),
                    resource = 1, // 默认来源类型为销售订单
                    productName = txtproname.Text.Trim(),
                    productCode = txtProcode.Text.Trim(),
                    specification = txtspecifi.Text.Trim(),
                    unitName = txtunit.Text.Trim(),
                    planNum = int.TryParse(txtPlannum.Text, out int planNum) ? planNum : 0,
                    planStart = DateTime.TryParse(dtpStart.text, out DateTime startDate) ? startDate : (DateTime?)null,
                    planEnd = DateTime.TryParse(dtpComple.text, out DateTime endDate) ? endDate : (DateTime?)null,
                    requireDate = DateTime.TryParse(dtpRequireDate.text, out DateTime reqDate) ? reqDate : (DateTime?)null,
                    planState = 1, // 默认状态
                    createName = "张三", 
                    createDate = DateTime.Now,
                    productId = 0, // 可以从产品选择中获取
                    state =1,
                    salesOrderId = int.TryParse(txtOrderCode.Text, out int orderId) ? orderId : 0 // 从销售订单选择中获取
                };

                // 序列化为JSON
                string jsonData = JsonConvert.SerializeObject(planData);

                // 发送POST请求到后端API
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync("http://localhost:5281/api/Plan/AddPlan", content);
                    
                    if (response.IsSuccessStatusCode)
                    {
                        string responseContent = await response.Content.ReadAsStringAsync();
                        var apiResponse = JsonConvert.DeserializeObject<AddPlanApiResponse>(responseContent);
                        
                        if (apiResponse.code == 200)
                        {
                            MessageBox.Show("生产计划添加成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // 清空表单
                            ClearForm();
                            // 刷新列表
                            await LoadPlanList();

                            // 基于新增的生产计划，同步生成一条生产工单
                            try
                            {
                                await CreateProductionOrderFromPlanAsync(planData);
                            }
                            catch (Exception exGen)
                            {
                                // 不中断主流程，仅提示
                                Console.WriteLine($"根据生产计划生成生产工单失败: {exGen.Message}");
                                MessageBox.Show($"生产工单生成失败: {exGen.Message}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            }
                        }
                        else
                        {
                            MessageBox.Show(string.Format("添加失败: {0}", apiResponse.msg), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show(string.Format("请求失败: {0}", response.StatusCode), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("添加生产计划失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 清空新增表单
        /// </summary>
        private void ClearForm()
        {
         
            txtPlanCode.Text = string.Empty;
            txtPlanName.Text = string.Empty;
            txtproname.Text = string.Empty;
            txtProcode.Text = string.Empty;
            txtspecifi.Text = string.Empty;
            txtunit.Text = string.Empty;
            txtPlannum.Text = string.Empty;
            txtOrderCode.Text = string.Empty;
            cboResource.SelectedIndex = 0; 
            dtpStart.text = "";
            dtpComple.text = "";
            dtpRequireDate.text = "";
        }

        /// <summary>
        /// 刷新计划列表
        /// </summary>
        private async Task LoadPlanList()
        {
              btnSearch_Click(null, null);
              
        }

        /// <summary>
        /// 根据新增的生产计划生成一条生产工单
        /// </summary>
        private async Task CreateProductionOrderFromPlanAsync(PlanData plan)
        {
            if (plan == null) return;

            // 生成工单编号：按 GDBH#### 递增；若无法获取历史编号，则回退为时间戳
            string nextCode = await GetNextProductionOrderCodeAsync();
            if (string.IsNullOrWhiteSpace(nextCode))
            {
                nextCode = "GDBH" + DateTime.Now.ToString("MMddHHmm");
            }

            string ResourceToText(int resource)
            {
                switch (resource)
                {
                    case 1: return "销售订单";
                    case 2: return "库存备货";
                    case 3: return "其他";
                    default: return "其他";
                }
            }

            var payload = new
            {
                // 基本字段
                ProductionOrdersCode = nextCode,
                ProductionOrdersName = "新产品工单",
                ProductionOrdersProgress = 0,
                AssociatePlans = plan.planName ?? string.Empty,
                PlanNumber = plan.planCode ?? string.Empty,
                Type = ResourceToText(plan.resource),
                ProductName = plan.productName ?? string.Empty,
                ProductCode = plan.productCode ?? string.Empty,
                SpecificationModel = plan.specification ?? string.Empty,
                ProductType = "成品",
                Unit = plan.unitName ?? string.Empty,
                BOM = "BOM" + DateTime.Now.ToString("yyyyMMddHHmmss"),
                Version = "1.1",
                PlannedQuantity = plan.planNum,
                ActualQuantity = 0,
                PlanStart = plan.planStart?.ToString("yyyy-MM-ddTHH:mm:ss"),
                PlanEnd = plan.planEnd?.ToString("yyyy-MM-ddTHH:mm:ss"),
                DemandDate = plan.requireDate?.ToString("yyyy-MM-ddTHH:mm:ss"),
                Batch = DateTime.Now.ToString("yyyyMMddHHmmss"),
                ActualStart = (string)null,
                ActualEnd = (string)null,
                Remark = "生产工单生成",
                State = 0
            };

            var json = JsonConvert.SerializeObject(payload);
            using (var http = new HttpClient())
            {
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var resp = await http.PostAsync("http://localhost:5257/api/ProductionOrders/AddProductionOrdersCommand", content);
                var txt = await resp.Content.ReadAsStringAsync();
                if (!resp.IsSuccessStatusCode)
                {
                    throw new Exception($"HTTP {resp.StatusCode}: {txt}");
                }
            }
        }

        /// <summary>
        /// 从后端获取最新的工单编号并计算下一个编号（GDBH####）
        /// </summary>
        private async Task<string> GetNextProductionOrderCodeAsync()
        {
            try
            {
                using (var http = new HttpClient())
                {
                    // 取较大的 PageSize 以便尽可能拿到最新的编号
                    var url = "http://localhost:5257/api/ProductionOrders/ProductionOrdersCommand?PageIndex=1&PageSize=200";
                    var resp = await http.GetAsync(url);
                    resp.EnsureSuccessStatusCode();
                    var json = await resp.Content.ReadAsStringAsync();
                    dynamic root = JsonConvert.DeserializeObject(json);
                    var arr = root?.data?.pageDatas ?? root?.data?.data;
                    int maxNo = 0;
                    if (arr != null)
                    {
                        foreach (var it in arr)
                        {
                            string code = (string)(it["productionOrdersCode"] ?? it["ProductionOrdersCode"]);
                            if (string.IsNullOrWhiteSpace(code)) continue;
                            if (code.StartsWith("GDBH", StringComparison.OrdinalIgnoreCase))
                            {
                                var numPart = new string(code.Skip(4).Where(char.IsDigit).ToArray());
                                if (int.TryParse(numPart, out int n))
                                {
                                    if (n > maxNo) maxNo = n;
                                }
                            }
                        }
                    }
                    int next = maxNo + 1;
                    return $"GDBH{next:0000}";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"获取下一个工单编号失败: {ex.Message}");
                return null;
            }
        }
        /// <summary>
        /// 处理DataGridView单元格点击事件
        /// </summary>
        private async void dgvPlanList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                // 添加调试信息
                Console.WriteLine($"CellClick: Row={e.RowIndex}, Column={e.ColumnIndex}, ColumnName={dgvPlanList.Columns[e.ColumnIndex].HeaderText}");
                
                // 检查是否点击了按钮列
                if (e.RowIndex >= 0 && e.ColumnIndex >= 0 && e.ColumnIndex < dgvPlanList.Columns.Count)
                {
                    var column = dgvPlanList.Columns[e.ColumnIndex];
                    if (column is DataGridViewButtonColumn)
                    {
                        // 获取当前行的数据
                        var currentRow = dgvPlanList.Rows[e.RowIndex];
                        
                        // 调试：输出当前行的所有数据
                        Console.WriteLine("当前行数据:");
                        for (int i = 0; i < currentRow.Cells.Count; i++)
                        {
                            var cell = currentRow.Cells[i];
                            var col = dgvPlanList.Columns[i];
                            Console.WriteLine($"  列{i}: {col.HeaderText} = {cell.Value} (类型: {cell.Value?.GetType().Name ?? "null"})");
                        }
                        
                        if (column.HeaderText == "修改")
                        {
                            // 从DataSource获取完整的PlanData对象
                            PlanData planData = null;
                            if (dgvPlanList.DataSource is List<PlanData> planList && e.RowIndex < planList.Count)
                            {
                                planData = planList[e.RowIndex];
                                Console.WriteLine($"从DataSource获取PlanData: planId={planData.planId}, salesOrderId={planData.salesOrderId}");
                            }
                            else
                            {
                                // 如果无法从DataSource获取，则使用更安全的方式从DataGridView获取数据
                                planData = new PlanData();
                                
                                // 使用DataPropertyName来获取数据，避免硬编码列索引
                                foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                {
                                    if (!string.IsNullOrEmpty(col.DataPropertyName))
                                    {
                                        var cellValue = currentRow.Cells[col.Index].Value;
                                        if (cellValue != null)
                                        {
                                            try
                                            {
                                                switch (col.DataPropertyName.ToLower())
                                                {
                                                    case "planid":
                                                        planData.planId = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "plancode":
                                                        planData.planCode = cellValue.ToString();
                                                        break;
                                                    case "planname":
                                                        planData.planName = cellValue.ToString();
                                                        break;
                                                    case "resource":
                                                        planData.resource = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "productname":
                                                        planData.productName = cellValue.ToString();
                                                        break;
                                                    case "productcode":
                                                        planData.productCode = cellValue.ToString();
                                                        break;
                                                    case "specification":
                                                        planData.specification = cellValue.ToString();
                                                        break;
                                                    case "unitname":
                                                        planData.unitName = cellValue.ToString();
                                                        break;
                                                    case "plannum":
                                                        planData.planNum = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "planstart":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                                            planData.planStart = start;
                                                        break;
                                                    case "planend":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                                            planData.planEnd = end;
                                                        break;
                                                    case "requiredate":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                                            planData.requireDate = require;
                                                        break;
                                                    case "planstate":
                                                        planData.planState = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "salesorderid":
                                                        if (int.TryParse(cellValue.ToString(), out int orderId))
                                                            planData.salesOrderId = orderId;
                                                        break;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                                            }
                                        }
                                    }
                                }
                                
                                // 设置默认值
                                planData.createName = "张三";
                                planData.createDate = DateTime.Now;
                                planData.productId = 0;
                                planData.state = 1;
                            }

                            // 打开修改窗体
                            var updateForm = new UpdateProductPlan(planData);
                            if (updateForm.ShowDialog() == DialogResult.OK)
                            {
                                // 修改成功后刷新列表
                                await LoadPlanList();
                            }
                        }
                        else if (column.HeaderText == "删除")
                        {
                            // 获取计划ID
                            int planId = 0;
                            if (dgvPlanList.DataSource is List<PlanData> dataSourceList && e.RowIndex < dataSourceList.Count)
                            {
                                planId = dataSourceList[e.RowIndex].planId;
                            }
                            else
                            {
                                // 尝试从第一列获取planId
                                var planIdCell = currentRow.Cells[0];
                                if (planIdCell.Value != null && int.TryParse(planIdCell.Value.ToString(), out int id))
                                {
                                    planId = id;
                                }
                            }
                            
                            if (planId > 0)
                            {
                                // 获取计划编号用于显示
                                string planCode = "";
                                if (dgvPlanList.DataSource is List<PlanData> dataSourceList2 && e.RowIndex < dataSourceList2.Count)
                                {
                                    planCode = dataSourceList2[e.RowIndex].planCode;
                                }
                                else
                                {
                                    // 尝试从planCode列获取
                                    foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                    {
                                        if (col.DataPropertyName?.ToLower() == "plancode")
                                        {
                                            planCode = currentRow.Cells[col.Index].Value?.ToString() ?? "";
                                            break;
                                        }
                                    }
                                }
                                
                                // 确认删除
                                var result = MessageBox.Show($"确定要删除计划编号为 {planCode} 的生产计划吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                                if (result == DialogResult.Yes)
                                {
                                    await DeletePlan(planId);
                                }
                            }
                            else
                            {
                                MessageBox.Show("无法获取计划ID，删除操作失败", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else if(column.HeaderText=="详情")
                        {
                            PlanData planData = null;
                            if (dgvPlanList.DataSource is List<PlanData> planList && e.RowIndex < planList.Count)
                            {
                                planData = planList[e.RowIndex];
                                Console.WriteLine($"从DataSource获取PlanData详情: planId={planData.planId}, planName={planData.planName}");
                            }
                            else
                            {
                                // 如果无法从DataSource获取，则使用更安全的方式从DataGridView获取数据
                                planData = new PlanData();
                                
                                // 使用DataPropertyName来获取数据，避免硬编码列索引
                                foreach (DataGridViewColumn col in dgvPlanList.Columns)
                                {
                                    if (!string.IsNullOrEmpty(col.DataPropertyName))
                                    {
                                        var cellValue = currentRow.Cells[col.Index].Value;
                                        if (cellValue != null)
                                        {
                                            try
                                            {
                                                switch (col.DataPropertyName.ToLower())
                                                {
                                                    case "planid":
                                                        planData.planId = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "plancode":
                                                        planData.planCode = cellValue.ToString();
                                                        break;
                                                    case "planname":
                                                        planData.planName = cellValue.ToString();
                                                        break;
                                                    case "resource":
                                                        planData.resource = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "productname":
                                                        planData.productName = cellValue.ToString();
                                                        break;
                                                    case "productcode":
                                                        planData.productCode = cellValue.ToString();
                                                        break;
                                                    case "specification":
                                                        planData.specification = cellValue.ToString();
                                                        break;
                                                    case "unitname":
                                                        planData.unitName = cellValue.ToString();
                                                        break;
                                                    case "plannum":
                                                        planData.planNum = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "planstart":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime start))
                                                            planData.planStart = start;
                                                        break;
                                                    case "planend":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime end))
                                                            planData.planEnd = end;
                                                        break;
                                                    case "requiredate":
                                                        if (DateTime.TryParse(cellValue.ToString(), out DateTime require))
                                                            planData.requireDate = require;
                                                        break;
                                                    case "planstate":
                                                        planData.planState = Convert.ToInt32(cellValue);
                                                        break;
                                                    case "salesorderid":
                                                        if (int.TryParse(cellValue.ToString(), out int orderId))
                                                            planData.salesOrderId = orderId;
                                                        break;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                Console.WriteLine($"转换列 {col.DataPropertyName} 的值时出错: {ex.Message}");
                                            }
                                        }
                                    }
                                }
                                
                                // 设置默认值
                                planData.createName = "张三";
                                planData.createDate = DateTime.Now;
                                planData.productId = 0;
                                planData.state = 1;
                                
                                Console.WriteLine($"从DataGridView获取PlanData详情: planId={planData.planId}, planName={planData.planName}");
                            }
                            
                            // 输出传递给详情窗体的完整数据
                            Console.WriteLine("=== 传递给ProductDetailMain的数据 ===");
                            Console.WriteLine($"计划ID: {planData.planId}");
                            Console.WriteLine($"计划编号: {planData.planCode}");
                            Console.WriteLine($"计划名称: {planData.planName}");
                            Console.WriteLine($"来源类型: {planData.resource}");
                            Console.WriteLine($"产品名称: {planData.productName}");
                            Console.WriteLine($"产品编号: {planData.productCode}");
                            Console.WriteLine($"规格型号: {planData.specification}");
                            Console.WriteLine($"计划数量: {planData.planNum}");
                            Console.WriteLine($"单位: {planData.unitName}");
                            Console.WriteLine($"计划开工时间: {planData.planStart}");
                            Console.WriteLine($"计划完工时间: {planData.planEnd}");
                            Console.WriteLine($"需求日期: {planData.requireDate}");
                            Console.WriteLine($"销售订单ID: {planData.salesOrderId}");
                            Console.WriteLine("=== 数据传递完成 ===");
                            
                            // 打开详情窗体
                            var detailForm = new ProductDetailMain(planData);
                            detailForm.ShowDialog();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"CellClick异常: {ex.Message}");
                MessageBox.Show(string.Format("操作失败: {0}", ex.Message), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       

      

        /// <summary>
        /// 删除生产计划
        /// </summary>
        /// <param name="planId">计划ID</param>
        private async Task DeletePlan(int planId)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    var deleteData = new { planId = planId };
                    var json = JsonConvert.SerializeObject(deleteData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    var response = await httpClient.PutAsync("http://localhost:5281/api/Plan/DelPlan", content);
                    var responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        var apiResponse = JsonConvert.DeserializeObject<SimpleApiResponse>(responseContent);
                        if (apiResponse.code == 200)
                        {
                            MessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            // 刷新列表
                            await LoadPlanList();
                        }
                        else
                        {
                            MessageBox.Show($"删除失败: {apiResponse.msg}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"删除异常: {ex.Message}");
                MessageBox.Show($"删除生产计划失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       
     
    }
}
